<?php

namespace app\api\logic;

use app\common\exception\BusinessException;

class BuildAIQuestionFormat
{
    private $question;

    private $questionBackground;

    public function __construct($question, $questionBackground)
    {
        $this->question = $question;
        $this->questionBackground = $questionBackground;
    }

    public function build()
    {
        // 检查参数
        $this->check();

        // 返回文本
        $response = '';

        // 背景信息
        $response .= $this->buildBackground();

        // 标题信息
        $response .= $this->buildQuestionAsk();

        // 选项信息
        $response .= $this->buildQuestionOptions();

        // 答案信息
        $response .= $this->buildAnswer();

        // 解析信息
        $response .= $this->buildExplanation();

        // 返回
        return $response;
    }

    private function buildExplanation()
    {
        $explanation = $this->question['explanation'] ?: '无题目解析';
        return '题目解析:' . $explanation . '<br>';
    }

    private function buildAnswer()
    {
        $correctOption = $this->question['correctOption'] ?: '无参考答案';
        return '题目答案:' . $correctOption . '<br>';
    }

    private function buildQuestionOptions()
    {
        $allOptions = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
        $allOptionText = [];
        foreach ($allOptions as $option) {
            $optionText = $this->question['answerOption'][$option] ?? '';
            if ($optionText) {
                $allOptionText[] = '选项' . $option . '.' . $optionText;
            }
        }
        if ($allOptionText) {
            return '题目选项:' . join('<br>', $allOptionText) . '<br>';
        }
        return '';
    }

    private function buildQuestionAsk()
    {
        return '题目内容:' . $this->question['questionAsk'] . '<br>';
    }

    private function buildBackground()
    {
        if (!$this->questionBackground) {
            return '';
        }
        return '题目背景:' . $this->questionBackground . '<br>';
    }


    /**
     * check
     * @throws BusinessException
     */
    public function check()
    {
        if (empty($this->question['questionAsk'])) {
            throw new BusinessException('题目标题不完整不支持解析');
        }
        if (empty($this->question['correctOption']) && empty($this->data['explanation'])) {
            throw new BusinessException('题目答案和题目解析同时为空不支持解析');
        }
    }
}